package com.example.shangjinlieren.tabbar.fraction;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.ability.fraction.FractionScheduler;

import java.util.ArrayList;
import java.util.List;

public  class FractionUtil {
    private Integer currentSaveIndex=0;//当前正在显示的索引值
    private List<Fraction> fractions ;
    private FractionAbility ability;
    public FractionUtil(List<Fraction> fractions,Integer currentSaveIndex,FractionAbility ability,int resourceTableId) {
        if (fractions == null || fractions.size() == 0) {
            throw new AssertionError("fractions 必须有值");
        }

        this.fractions = fractions;
        this.ability=ability;
        this.currentSaveIndex =currentSaveIndex;
        initTabberPage(resourceTableId);
    }
    public void initTabberPage(int resourceTableId){
        if (this.currentSaveIndex < 0 || this.currentSaveIndex >= fractions.size()) {
            throw new AssertionError("初始化索引值是非法的");
        }

        FractionScheduler scheduler = getFractionManager().startFractionScheduler();

        for (Fraction fraction : fractions) {
            scheduler.add(resourceTableId, fraction)
                    .hide(fraction);
        }

        scheduler.show(this.fractions.get(this.currentSaveIndex))
                .submit();

    }
    /**
     * 获取Fraction管理器对象
     @return
     */
    public  FractionManager getFractionManager(){
//        Ability ability = this.abilitySlice.getAbility();
        if(this.ability instanceof FractionAbility){
            FractionAbility fractionAbility = (FractionAbility) this.ability;
            return fractionAbility.getFractionManager();
        }
        return null;
    }

    /**
     *兼容老版本 保留
     * @param indexHide 隐藏的索引
     */
    public  void hide(Integer indexHide){
        getFractionManager()
        .startFractionScheduler()
        .hide(this.fractions.get(indexHide))
        .submit();
    }

    /**
     *
     * @param indexshow 显示点击的页面索引
     */
    public void show(int indexshow){
        if (indexshow >= 0 && indexshow < fractions.size()) {
            getFractionManager()
                    .startFractionScheduler()
                    .hide(this.fractions.get(this.currentSaveIndex))
                    .show(this.fractions.get(indexshow))
                    .submit();

            this.currentSaveIndex= indexshow;
        }

    }
}
